package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public UserLoginVO loginByOpenId(UserLoginDTO userLoginDTO) {
        UserLoginVO userLoginVO = new UserLoginVO();
        String openId = getOpenId(userLoginDTO.getCode());
        // openid是空，抛出业务异常
        if (openId == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 存在直接登录，返回实体类user
        User user = userMapper.selectByOpenId(openId);
        // 如果不存在则创建一个用户
        if (user == null) {
            user = User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insertUser(user);
        }

        // 生成token
        HashMap<String, Object> payload = new HashMap<>();
        payload.put(JwtClaimsConstant.USER_ID, user.getId());
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), payload);

        // 封装需要返回的VO对象，id，token，openid
        userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .token(jwt)
                .openid(openId)
                .build();

        return userLoginVO;
    }

    private String getOpenId(String code) {
        // 使用httpclient
        Map paramData = new HashMap();
        paramData.put("appid", weChatProperties.getAppid());
        paramData.put("secret", weChatProperties.getSecret());
        paramData.put("js_code", code);
        paramData.put("grant_type", "authorization_code");
        log.info("参数：{}", paramData);
        String content = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paramData);

        // 返回JSON串，需要的数据是openid
        log.info("微信返回：{}", content);
        // 通过JSON串拿数据，通过FastJSON获得数据
        JSONObject jsonObject = JSON.parseObject(content);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
